package org.example.SolutionNew002;

public class LinkedList06 {
    public static void main(String[] args) {
        LinkedList06 l = new LinkedList06();
        ListNode head1 = new ListNode(1);
        head1.next = new ListNode(2);
        head1.next.next = new ListNode(4);
        ListNode head2 = new ListNode(1);
        head2.next = new ListNode(3);
        head2.next.next = new ListNode(4);
        ListNode res=l.mergeTwoLists(head1, head2);
        while(res!=null){
            System.out.println(res.val);
            res=res.next;
        }
    }

    public ListNode mergeTwoLists1(ListNode list1, ListNode list2) {
        ListNode res = new ListNode(0);
        ListNode curr = res;
        if(list1==null&&list2==null){
            return null;
        }else if(list1==null){
            return list2;
        }else if(list2==null){
            return list1;
        }
        while(list1!=null&&list2!=null){
            if(list1.val<list2.val){
                curr.next = list1;
                curr = curr.next;
                list1 = list1.next;
            }else{
                curr.next = list2;
                curr = curr.next;
                list2 = list2.next;
            }
        }
        if(list2!=null){
            curr.next = list2;
        }
        if(list1!=null){
            curr.next = list1;
        }
        return res.next;
    }

    //递归
    public ListNode mergeTwoLists(ListNode list1, ListNode list2) {
        if(list1==null){
            return list2;
        }
        if(list2==null){
            return list1;
        }
        if(list1.val<list2.val){
            list1.next=mergeTwoLists(list1.next,list2);
            return list1;
        }else{
            list2.next=mergeTwoLists(list1,list2.next);
            return list2;
        }
    }
}
